import { FastifyPluginAsync } from 'fastify'

const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
  fastify.get('/', async function (request, reply) {
    return { root: true }
  })

  // 使用 @fastify/mongodb 的 hello 接口
  fastify.get('/hello1/:id', async function (request, reply) {
    // 使用一个简单的内存锁，防止同一时间多次调用
    // @ts-ignore
    const id = request.params.id
    if ((fastify as any)._helloLockId === id) {
      return reply.status(429).send({ error: '请求过于频繁，请稍后再试' })
    }
    (fastify as any)._helloLockId = id
    try {
      console.log('访问/hello接口')

      // 获取MongoDB集合
      const db = fastify.mongo.db
      // @ts-ignore
      const collection = db.collection('messages')

      // 查询数据
      const result = await collection.findOne({ id })

      if(!result){
        // 如果没有数据，插入一条
        await collection.insertOne({
          id,
          type: 'greeting16',
          message: 'Hello, MongoDB!',
          createdAt: new Date()
        })
      }
      return { message: `Hello, MongoDB! (${result ? '已存在' : '新插入'})`, id: result?.id, timestamp: result?.createdAt }
    } catch (err) {
      console.error('MongoDB操作失败:', err)
      return { error: '数据库操作失败', message: 'Hello, World! (fallback)' }
    }finally {
      (fastify as any)._helloLockId = null
    }
  })

  // 带参数的接口
  fastify.get('/hello/:name', async function (request, reply) {
    const { name } = request.params as { name: string }
    return { message: `Hello, ${name}!` }
  })

  // POST接口示例
  fastify.post('/data', async function (request, reply) {
    const body = request.body
    // 处理请求数据
    return { success: true, data: body }
  })
}

export default root
